﻿create PROCEDURE Sync.SP_Committees_ApplyChanges
@RawValues XML 
AS 
BEGIN
	 
		DECLARE @Committees_Temp TABLE 
		(
			CommitteeID UniqueIdentifier,
			[CommitteeName] nvarchar(50),
				[CenterID] uniqueidentifier,
				[IsMainCommittee] bit,
			IsDeleted BIT, 
			LastUpdatedDate DATETIME
		)
		
	   INSERT INTO @Committees_Temp 
	   SELECT	Tbl.Col.value('CommitteeID[1]','uniqueidentifier') CommitteeID,
                Tbl.Col.value('CommitteeName[1]', 'nvarchar(50)') [CommitteeName],
Tbl.Col.value('CenterID[1]', 'uniqueidentifier') [CenterID],
Tbl.Col.value('IsMainCommittee[1]', 'bit') [IsMainCommittee],
				Tbl.Col.value('IsDeleted[1]', 'bit') IsDeleted,
				Tbl.Col.value('LastUpdatedDate[1]','DateTime') LastUpdatedDate
	   FROM   @RawValues.nodes('/DocumentElement/Committees') Tbl(Col)
----------------------------------------------------------------------------------------

-- Insert ------------------------------------------------------------------------------

	INSERT INTO [dbo].[Committees] ([CommitteeID],[CommitteeName],[CenterID],[IsMainCommittee])
	SELECT t.[CommitteeID],t.[CommitteeName],t.[CenterID],t.[IsMainCommittee]
	FROM  @Committees_Temp t
	WHERE t.IsDeleted = 0
    AND NOT EXISTS
    (
        SELECT 1 FROM sync.Committees_Tracking s
        WHERE t.CommitteeID = s.CommitteeID
    )
	-- put conflicts here.
	
-- Update -------------------------------------------------------------------------------
     
	UPDATE [dbo].[Committees]
	SET [Committees].[CommitteeName] = t.[CommitteeName],[Committees].[CenterID] = t.[CenterID],[Committees].[IsMainCommittee] = t.[IsMainCommittee] 
	FROM [dbo].[Committees] s JOIN @Committees_Temp t 
    ON t.CommitteeID = s.CommitteeID
	WHERE	t.IsDeleted = 0 
	AND		t.LastUpdatedDate IS NOT NULL
	AND		t.LastUpdatedDate >= 
				 isnull((SELECT TOP 1 LastUpdatedDate 
				  FROM sync.Committees_Tracking r
				  WHERE t.CommitteeID = r.CommitteeID)
                  ,t.LastUpdatedDate)
	-----------------------------------------------------------------------------------------

-- Delete -------------------------------------------------------------------------------

	DELETE [dbo].[Committees]
    FROM @Committees_Temp t JOIN [dbo].[Committees] s
    ON t.CommitteeID = s.CommitteeID
	WHERE t.IsDeleted = 1

-----------------------------------------------------------------------------------------
	
END














